import os
import socket
from pydantic_settings import BaseSettings
from typing import Dict, Optional, ClassVar

# 获取主机IP地址
def get_host_ip():
    try:
        # 尝试获取主机IP
        s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        s.connect(("8.8.8.8", 80))
        ip = s.getsockname()[0]
        s.close()
        return ip
    except Exception:
        return "localhost"  # 如果获取失败，返回localhost

class Settings(BaseSettings):
    # 基本API配置
    HOST: str = "0.0.0.0"
    PORT: int = 8060
    DEBUG: bool = True
    
    # 获取主机IP，用于生成URL
    HOST_IP: str = get_host_ip()
    
    # Docker相关配置
    DOCKER_COMPOSE_TEMPLATE: str = "templates/docker-compose.yml.j2"
    DOCKER_DATA_PATH: str = os.path.join(os.path.expanduser("~"), "mobox_data")
    
    # 用户数据相关配置
    USER_DATA_PATH: str = os.path.join(DOCKER_DATA_PATH, "users")
    COURSE_BASE_PATH: str = "/home/mobox/course"  # 修改为mobox用户home目录下的course
    
    # 课程文件相关配置
    COURSE_FILES_SERVER: str = "http://example.com/course_files"  # 固定服务器地址，需要替换为实际地址
    
    # 认证配置（暂时设为None关闭认证）
    API_TOKEN: Optional[str] = None
    
    # Docker服务映射端口范围
    PORT_RANGE_START: int = 8001
    PORT_RANGE_END: int = 9000
    
    # 是否使用阿里云OSS下载文件
    USE_OSS: bool = True  # 设置为 False 将使用原有的 HTTP 下载方式
    
    # Jupyter服务端口
    JUPYTER_PORT: int = 5173
    
    # 阿里云OSS配置
    OSS_ENDPOINT: str = 'https://oss-cn-beijing.aliyuncs.com'
    OSS_BUCKET_NAME: str = 'lwx-ai-couse'
    OSS_REGION: str = 'cn-beijing'
    OSS_ACCESS_KEY_ID: str = 'LTAI5tGzV7ibrgjoWuMuJPpF'
    OSS_ACCESS_KEY_SECRET: str = 'RTsrrrU08eH6mkJiDCewRR1XJreDP6'
    
    model_config = {
        "env_file": ".env",
        "case_sensitive": True
    }

settings = Settings()

# 确保必要的目录存在
os.makedirs(settings.DOCKER_DATA_PATH, exist_ok=True)
os.makedirs(settings.USER_DATA_PATH, exist_ok=True)
os.makedirs("templates", exist_ok=True)
os.makedirs("api", exist_ok=True)
os.makedirs("services", exist_ok=True)

# 确保基础目录存在
os.makedirs(settings.COURSE_BASE_PATH, exist_ok=True) 